import config from "../config.js"
import common from "./common.js"

// #ifdef H5
// import wxjssdk from "components/hzjc/utils/auth/wxjssdk.js"
// #endif

// #ifdef MP-WEIXIN
// import mpWeixin from "@/components/hzjc/utils/auth/mpWeixin.js"
// #endif

let request = {}

request.requestUrl = config.isTest ? config.testHost + config.testEntry : config.host + config.entry
request.user_agent = common.userAgent()
/**
 * post请求
 * @param {string} url 请求地址
 * @param {object} data 请求参数
 * 2020-08-13
 */
request.post = function(url, data = {}) {
	//获取uid
	let uid
	if (this.user_agent == 'h5' || this.user_agent == 'weixin') {
		uid = uni.getStorageSync('uid') ? uni.getStorageSync('uid') : 2
	} else {
		uid = config.uid
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: this.requestUrl + url,
			data: data,
			method: 'POST',
			header: {
				'content-type': 'application/json',
				'token': uni.getStorageSync('token'),
				'code-agent': this.user_agent,
				'uid': uid
			},
			dataType: 'json',
			success: res => {
				resolve(res.data)
			},
			fail: res => {
				reject(res)
			}
		})
	})
}

/**
 * 获取数据
 * @param {string} url 请求地址
 * @param {object} data 请求参数
 * @param {object} initial 其他参数
 * @param {boolean} initial.loading false--不显示加载中  true--显示加载中
 * @param {boolean} initial.showErrMsg false--不显示错误文案  true--显示错误文案
 * 2020-08-13
 */
request.getData = function(url, data = {}, initial = {}) {
	let that = this

	if (initial.hasOwnProperty('loading') && initial.loading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
	}
	
	// 没有定义showErrMsg参数时，默认为true
	if(!initial.hasOwnProperty('showErrMsg')){
		initial.showErrMsg = true
	}

	return new Promise((resolve, reject) => {
		this.post(url, data).then(res => {
			if (initial.hasOwnProperty('loading') && initial.loading) {
				uni.hideLoading()
			}

			if (res.code === 1) {
				resolve(res)
			} else {
				if (initial.showErrMsg) {
					if (!res.msg) res.msg = '未知错误'
					common.alert(res.msg).then(() => {
						resolve(res)
					})
				} else {
					resolve(res)
				}

			}
		}).catch(res => {
			common.alert('网络异常').then(() => {
				reject(res)
			});
		})
	});
}

//没有用
request.getDataNoMessage = function(url, initial = {}) {
	return new Promise((resolve, reject) => {
		let that = this;
		if (initial.hasOwnProperty('loading') && initial.loading === 1) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}
		if (!initial.hasOwnProperty('data')) {
			initial.data = {};
		}
		initial.data.user_id = uni.getStorageSync('user_id') || '';
		// #ifdef APP-PLUS
		initial.data.uuid = uni.getStorageSync('uuid');
		// #endif
		this.post(url, initial.data).then(res => {
			if (initial.hasOwnProperty('loading') && initial.loading === 1) {
				uni.hideLoading();
			}
			resolve(res);
		}).catch(res => {
			uni.showModal({
				title: '',
				content: '网络出错，请稍后重试',
				showCancel: false,
				cancelText: '',
				confirmText: '确定',
				success: res => {},
				fail: () => {},
				complete: () => {}
			});
			reject(res);
		})
	});
}

/**
 * 加载下一页 first_page=1时，自动清空列表加载第1页 first_page!=1时，加载下一页
 * 2022-08-08
 */
request.getList = function(url, data = {}, initial = {}) {
	return new Promise((resolve, reject) => {
		if (initial.that.loadStatus == 'loading' || (initial.that.loadStatus == 'finished' && initial
				.first_page != 1)) {
			return false; //正在加载中或者已经加载完成不触发加载事件
		}
		initial.that.loadStatus = 'loading' //切换jc-list组件状态

		if (initial.hasOwnProperty('loading') && initial.loading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}

		//判断当前加载页数
		let loading_page;
		if (initial.first_page != 1) {
			loading_page = initial.that.page || 0;
			loading_page = initial.that.page + 1;
		} else {
			loading_page = 1;
			initial.that.list = [];
		}

		data.page = loading_page;
		this.post(url, data).then(res => {
			initial.that.loadStatus = '' //切换jc-list组件状态
			if (initial.hasOwnProperty('loading') && initial.loading) {
				uni.hideLoading();
			}

			if (res.code == 1) {
				console.log(res)
				let data_list = res.data; //返回数据里面的列表数据

				if (!data_list.total) {
					initial.that.loadStatus = 'nodata';
				} else if (data_list.current_page >= data_list.last_page) {
					initial.that.loadStatus = 'finished';
				}
				if (data_list.data.length) {
					let list = initial.that.list;
					list = list.concat(data_list.data);
					initial.that.list = list;
					initial.that.page = data.page;
				}
				resolve(res);
			} else {
				initial.that.loadStatus = 'hasError';
			}
		}).catch(res => {
			reject(res)
		});
	})
}

/**
 * 加载上一页，通过最上方的ID加载上一页数据
 * {param} string url 请求连接
 * {param} object data 请求时携带请求参数
 * {param} object initial 其他附件参数
 * 					that: this
 * 					first_page: 1--加载第一页，自动清空列表 0--加载上一页，不清空列表
 * 					loading : true--显示加载蒙层，fasle--不显示加载蒙层
 * 2022-08-08
 */
request.getUpList = function(url, data = {}, initial = {}) {
	return new Promise((resolve, reject) => {
		// 正在加载中或者已经加载完成不触发加载事件
		if (initial.that.loadStatus == 'loading' || (initial.that.loadStatus == 'finished' && initial
				.first_page != 1)) {
			return false
		}

		// 切换jc-list组件状态
		initial.that.loadStatus = 'loading'

		// 显示加载浮层时加载过程中显示蒙层
		if (initial.hasOwnProperty('loading') && initial.loading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}

		this.post(url, data).then(res => {
			// 切换jc-list组件状态
			initial.that.loadStatus = ''

			// 显示加载浮层时加载完成隐藏蒙层
			if (initial.hasOwnProperty('loading') && initial.loading) {
				uni.hideLoading();
			}

			// 正常获得数据
			if (res.code == 0) {
				// 返回数据
				let data_list = res.data.up_list

				// 再上面没有数据了
				if (data_list.last_page <= 1) {
					initial.that.loadStatus = 'finished'
				}

				// 追加列表数据
				if (data_list.data.length) {
					// 读取现有列表数据
					let up_list = initial.that.up_list

					// 向上追加数据
					up_list = data_list.data.concat(up_list)

					// 赋值给页面变量up_list
					initial.that.up_list = up_list
				}
				resolve(res)
				// 没有获得数据
			} else {
				initial.that.loadStatus = 'hasError'
			}
		}).catch(res => {
			reject(res)
		})
	})
}

/**
 * 通过last_id加载下一页（一般用于订单删除不刷新页面）
 * @param string url 请求接口地址
 * @param object data 请求数据
 * @param object initial 请求的其他数据
 * 					that: this
 * 					first_page: 1--加载第一页，自动清空列表 0--加载上一页，不清空列表
 * 					loading : true--显示加载蒙层，fasle--不显示加载蒙层
 * @date 2022-04-29
 */
request.getListByLastId = function(url, data = {}, initial = {}) {
	return new Promise((resolve, reject) => {
		// console.log(initial.that.loadStatus)
		// console.log(initial.first_page)
		if (initial.first_page == 1) {
			initial.that.lastId = ''
		}
		
		// 正在加载中或者已经加载完成不触发加载事件
		if (initial.that.loadStatus == 'loading' || (initial.that.loadStatus == 'finished' && initial
				.first_page != 1)) {
			return false
		}
		// 切换jc-list组件状态为加载中
		initial.that.loadStatus = 'loading'

		if (initial.hasOwnProperty('loading') && initial.loading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}

		// 判断当前加载页数
		if (initial.first_page == 1) {
			initial.that.list = []
		}

		// 列表最后一条数据ID
		data.last_id = initial.that.lastId
		this.post(url, data).then(res => {
			// 切换jc-list组件状态
			initial.that.loadStatus = ''
			if (initial.hasOwnProperty('loading') && initial.loading) {
				uni.hideLoading()
			}

			if (res.code == 0) {
				let data_list = res.data.list //返回数据里面的列表数据

				if (initial.first_page == 1 && !data_list.length) {
					initial.that.loadStatus = 'nodata'
				} else if (initial.first_page != 1 && !data_list.length) {
					initial.that.loadStatus = 'finished'
				}

				if (data_list.length) {
					let list = initial.that.list
					list = list.concat(data_list)
					initial.that.list = list
					// 最后一条数据ID
					initial.that.lastId = list[list.length - 1].id
				}
				resolve(res);
			} else {
				initial.that.loadStatus = 'hasError';
			}
		}).catch(res => {
			reject(res)
		});
	})
}

/**
 * 校验token
 * 2022-04-29
 */
request.token = function() {
	return new Promise((resolve, reject) => {
		let unexpected = false
		// #ifdef APP-PLUS
		if (!uni.getStorageSync('access_token') && uni.getStorageSync('device_id')) {
			unexpected = true
		}
		// #endif

		// #ifdef MP-WEIXIN|MP-QQ|MP-ALIPAY
		if (!uni.getStorageSync('access_token') && uni.getStorageSync('openid')) {
			unexpected = true
		}
		// #endif

		// #ifdef H5
		if (common.userAgent() == 'weixin') { //微信浏览器，一般用于微信公众号
			if (!uni.getStorageSync('access_token') && uni.getStorageSync('openid')) {
				unexpected = true
			}
		}
		// #endif
		if (unexpected || (uni.getStorageSync('access_token') && uni.getStorageSync(
					'access_token_expire_time') < common
				.curTimestamp())) { //access_token意外丢失 | access_token已过期，清空缓存和openid拉取新的token
			uni.removeStorageSync('access_token')
			uni.removeStorageSync('access_token_expire_time')
			uni.removeStorageSync('user_id')

			// #ifdef APP-PLUS
			uni.removeStorageSync('device_id')
			// #endif

			// #ifdef MP-WEIXIN|MP-QQ|MP-ALIPAY
			uni.removeStorageSync('openid')
			// #endif

			// #ifdef H5
			if (common.userAgent() == 'weixin') { //微信浏览器，一般用于微信公众号
				uni.removeStorageSync('openid')
			}
			// #endif

			resolve('')
		} else if (uni.getStorageSync('access_token') && uni.getStorageSync('access_token_expire_time') -
			common.curTimestamp() <= 86400) { //临近24小时过期去申请新的token
			request.getData('base/token/api/Token/signNewToken').then((res) => {
				uni.setStorageSync('access_token', res.data.access_token)
				uni.setStorageSync('access_token_expire_time', res.data.access_token_expire_time)
				resolve(res)
			}).catch(res => {
				reject(res)
			})
		} else {
			resolve('')
		}
	})
}

export default request;
